package com.ashley.phonemsn

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.IBinder
import android.telephony.SmsMessage
import android.util.Log
import androidx.core.app.NotificationCompat

/**
 * 短信拦截服务
 * 用于拦截系统短信并重定向到应用内处理
 */
class SmsInterceptService : Service() {
    private val TAG = "SmsInterceptService"
    private val CHANNEL_ID = "sms_intercept_channel"
    private val NOTIFICATION_ID = 1002

    private var smsReceiver: BroadcastReceiver? = null
    private var isIntercepting = false

    @SuppressLint("ForegroundServiceType")
    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "短信拦截服务已创建")
        
        // 创建前台服务通知
        createNotificationChannel()
        startForeground(NOTIFICATION_ID, createNotification())
        
        // 设置短信拦截
        setupSmsInterception()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "短信拦截服务已启动")
        
        // 处理启动参数
        intent?.let {
            when (it.action) {
                ACTION_START_INTERCEPT -> {
                    startInterception()
                }
                ACTION_STOP_INTERCEPT -> {
                    stopInterception()
                }
            }
        }
        
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null

    /**
     * 设置短信拦截
     */
    private fun setupSmsInterception() {
        try {
            smsReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context?, intent: Intent?) {
                    if (intent?.action == "android.provider.Telephony.SMS_RECEIVED") {
                        Log.d(TAG, "拦截到系统短信")
                        
                        if (isIntercepting) {
                            // 拦截短信并处理
                            interceptSms(intent, this)
                        }
                    }
                }
            }
            
            // 注册短信接收广播接收器
            val filter = IntentFilter("android.provider.Telephony.SMS_RECEIVED")
            filter.priority = 999 // 设置高优先级以优先处理
            registerReceiver(smsReceiver, filter)
            
            Log.d(TAG, "短信拦截已设置")
        } catch (e: SecurityException) {
            Log.e(TAG, "设置短信拦截权限不足", e)
        } catch (e: Exception) {
            Log.e(TAG, "设置短信拦截失败", e)
        }
    }

    /**
     * 拦截并处理短信
     */
    private fun interceptSms(intent: Intent, receiver: BroadcastReceiver) {
        try {
            val bundle = intent.extras
            if (bundle != null) {
                val pdus = bundle["pdus"] as? Array<Any>
                Log.d(TAG, "拦截到短信PDUs数量: ${pdus?.size ?: 0}")

                if (pdus != null && pdus.isNotEmpty()) {
                    val fullMessageBuilder = StringBuilder()
                    var senderAddress: String? = null

                    for (pdu in pdus) {
                        try {
                            val smsMessage = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                val format = bundle.getString("format")
                                SmsMessage.createFromPdu(pdu as ByteArray, format)
                            } else {
                                SmsMessage.createFromPdu(pdu as ByteArray)
                            }

                            if (senderAddress == null) {
                                senderAddress = smsMessage.originatingAddress
                                senderAddress = senderAddress?.replace("[^0-9]".toRegex(), "")
                            }

                            fullMessageBuilder.append(smsMessage.messageBody)
                        } catch (e: Exception) {
                            Log.e(TAG, "处理短信PDU失败", e)
                        }
                    }

                    val fullMessage = fullMessageBuilder.toString()
                    Log.d(TAG, "拦截到短信 - 发送者: $senderAddress, 内容: $fullMessage")

                    // 阻止系统短信应用接收此短信
                    receiver.abortBroadcast()
                    
                    // 发送广播通知UI层有新的拦截短信
                    sendInterceptBroadcast(senderAddress, fullMessage)
                    
                    // 记录拦截的短信
                    logInterceptedSms(senderAddress, fullMessage)
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "拦截短信处理失败", e)
        }
    }

    /**
     * 发送拦截短信广播
     */
    private fun sendInterceptBroadcast(senderAddress: String?, message: String) {
        try {
            val broadcastIntent = Intent(ACTION_SMS_INTERCEPTED).apply {
                putExtra(EXTRA_SENDER_ADDRESS, senderAddress)
                putExtra(EXTRA_MESSAGE_CONTENT, message)
                putExtra(EXTRA_TIMESTAMP, System.currentTimeMillis())
            }
            
            sendBroadcast(broadcastIntent)
            Log.d(TAG, "已发送短信拦截广播")
        } catch (e: Exception) {
            Log.e(TAG, "发送短信拦截广播失败", e)
        }
    }

    /**
     * 记录拦截的短信
     */
    private fun logInterceptedSms(senderAddress: String?, message: String) {
        try {
            // 这里可以添加将拦截的短信保存到数据库的逻辑
            Log.i(TAG, "短信已拦截 - 发送者: $senderAddress, 内容: $message")
        } catch (e: Exception) {
            Log.e(TAG, "记录拦截短信失败", e)
        }
    }

    /**
     * 开始拦截
     */
    private fun startInterception() {
        isIntercepting = true
        Log.d(TAG, "短信拦截已启动")
        
        // 更新通知
        updateNotification("短信拦截服务 - 拦截中")
    }

    /**
     * 停止拦截
     */
    private fun stopInterception() {
        isIntercepting = false
        Log.d(TAG, "短信拦截已停止")
        
        // 更新通知
        updateNotification("短信拦截服务 - 已停止")
    }

    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "短信拦截服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "短信拦截服务正在运行，用于拦截系统短信"
            }
            
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    /**
     * 创建前台服务通知
     */
    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("短信拦截服务")
            .setContentText("正在监听短信")
            .setSmallIcon(android.R.drawable.ic_dialog_email)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()
    }

    /**
     * 更新通知
     */
    private fun updateNotification(text: String) {
        try {
            val notification = NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("短信拦截服务")
                .setContentText(text)
                .setSmallIcon(android.R.drawable.ic_dialog_email)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build()
            
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.notify(NOTIFICATION_ID, notification)
        } catch (e: Exception) {
            Log.e(TAG, "更新通知失败", e)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "短信拦截服务已销毁")
        
        // 停止拦截
        stopInterception()
        
        // 取消注册广播接收器
        try {
            smsReceiver?.let {
                unregisterReceiver(it)
            }
        } catch (e: Exception) {
            Log.w(TAG, "取消注册广播接收器时出错", e)
        }
        smsReceiver = null
    }

    companion object {
        const val ACTION_START_INTERCEPT = "com.ashley.phonemsn.ACTION_START_SMS_INTERCEPT"
        const val ACTION_STOP_INTERCEPT = "com.ashley.phonemsn.ACTION_STOP_SMS_INTERCEPT"
        const val ACTION_SMS_INTERCEPTED = "com.ashley.phonemsn.ACTION_SMS_INTERCEPTED"
        const val EXTRA_SENDER_ADDRESS = "sender_address"
        const val EXTRA_MESSAGE_CONTENT = "message_content"
        const val EXTRA_TIMESTAMP = "timestamp"
        
        /**
         * 启动短信拦截服务
         */
        fun startService(context: Context) {
            val intent = Intent(context, SmsInterceptService::class.java).apply {
                action = ACTION_START_INTERCEPT
            }
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
        }
        
        /**
         * 停止短信拦截服务
         */
        fun stopService(context: Context) {
            val intent = Intent(context, SmsInterceptService::class.java).apply {
                action = ACTION_STOP_INTERCEPT
            }
            context.stopService(intent)
        }
    }
}